package com.vogue.api.common.security.granter;

import cn.hutool.crypto.SecureUtil;
import com.alibaba.fastjson.JSONObject;
import com.vogue.api.common.security.model.Oauth2User;
import com.vogue.api.common.security.service.Oauth2UserDetailsService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.OAuth2RequestFactory;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;

import java.util.Map;

/**
 * 账号(手机号)密码获取token
 */
public class MobilePasswordTokenGranter extends AbstractCustomTokenGranter {
    protected Logger logger = LoggerFactory.getLogger(getClass());
    protected Oauth2UserDetailsService userDetailsService;

    public MobilePasswordTokenGranter(Oauth2UserDetailsService userDetailsService, AuthorizationServerTokenServices tokenServices, ClientDetailsService clientDetailsService, OAuth2RequestFactory requestFactory) {
        super(tokenServices, clientDetailsService, requestFactory, "password");
        this.userDetailsService = userDetailsService;
    }

    @Override
    protected Oauth2User getCustomUser(Map<String, String> parameters) {
        logger.error("MobilePasswordToken: "+ JSONObject.toJSON(parameters));
        String mobile = parameters.get("mobile");
        String password = parameters.get("password");
        return userDetailsService.loadUserByMobileAndPassword(mobile, SecureUtil.md5(password));
    }

}
